package cn.edu.buaa.cnsatm.traffic_big_data_server.highway.service;

import cn.edu.buaa.cnsatm.traffic_big_data_server.highway.dao.HighwayCongestionDAO;
import cn.edu.buaa.cnsatm.traffic_big_data_server.highway.dao.RoadDAO;
import cn.edu.buaa.cnsatm.traffic_big_data_server.highway.model.OSMRoadModel;
import cn.edu.buaa.cnsatm.traffic_big_data_server.util.DateUtil;
import cn.edu.buaa.cnsatm.traffic_big_data_server.util.JDBCUtil;
import cn.edu.buaa.cnsatm.traffic_big_data_server.util.Point2D;
import cn.edu.buaa.cnsatm.traffic_big_data_server.util.WebSpiderUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @name = LX
 * @classname = RoadService
 * @description = 存放道路信息
 * @date = 2019/12/9
 */
public class RoadService {
    public static Point2D left_bottom = new Point2D(115.382069,39.48948);  //设置区域左下角坐标（百度坐标系）
    public static Point2D right_top = new Point2D(117.516155,41.088451);  //设置区域左下角坐标（百度坐标系）
    final static String ROAD_NAME_URL = "http://api.map.baidu.com/place/v2/search?";
    final static String API_KEY = "SjfEmLN3QGQK5C9nDLMjhmiBGhlTXzUB";
    public static void getBeijingRoadNameFromAndSaveToDatabase(int n, int init_i, int init_j, int init_k){
        final String queryType = "道路";
        double xCellLength = (right_top.getX() - left_bottom.getX()) / n;
        double yCellLength = (right_top.getY() - left_bottom.getY()) / n;
        for(int i = init_i; i < n; i++){
            for(int j = init_j; j < n; j++){
                //获取切出来的方格的左下右上坐标

                Point2D cellLeftBottom = new Point2D(left_bottom.getX() + i * xCellLength, left_bottom.getY() + j * yCellLength);
                Point2D cellRightTop = new Point2D(right_top.getX() + i * xCellLength, right_top.getY() + j * yCellLength);
                for(int k = 0; k < 400; k++){
                    String queryURL = ROAD_NAME_URL + "query=" + queryType
                            + "&page_size=1&page_num=" + k + "&scope=1&bounds=" + cellLeftBottom.getY() + ","
                            + cellLeftBottom.getX() + "," + cellRightTop.getY() + ","  + cellRightTop.getX()
                            + "&output=json&ak=" + API_KEY;
                    System.out.println(queryURL);
                    System.out.println("i = " + i + "; j = " + j + "; k = " + k);
                    try{
                        JSONObject jo = JSON.parseObject(WebSpiderUtil.getJsonFromURL(queryURL));
                        Thread.sleep(500);
                        JSONArray ja = jo.getJSONArray("results");
                        for(int p = 0; p < ja.size(); p++){
                            if(!ja.getJSONObject(p).getString("city").equals("北京市")){
                                continue;
                            }
                            else{
                                String roadName = ja.getJSONObject(p).getString("name");
                                System.out.println(roadName);
                                RoadDAO.insertBeijingRoadName(roadName);
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                        continue;
                    }
                }

            }
        }
    }
    public static List<String> getBeijingRoadNameList() throws SQLException {
        /**
         * @description = 将OSM中的北京路名转成列表
         * @date = 2019/12/11
         */
        ResultSet nameSet = RoadDAO.getBeijingRoadName();
        List<String> nameList = new ArrayList<>();
        while (nameSet.next()){
            String roadName = nameSet.getString("name");
            nameList.add(roadName);
        }
        return nameList;
    }
    public static List<String> getInvalidRoadNameListFromOSM(String continueName) throws SQLException, InterruptedException {
        List<String> nameList = getBeijingRoadNameList();
        List<String> invalidNameList = new ArrayList<>();
        boolean goon = false;
        for(String roadName: nameList){
            if(roadName.equals(continueName)){
               goon = true;
            }
            if(goon == false){
                continue;
            }
            if(!isValidOSMRoadName(roadName, continueName)){
                invalidNameList.add(roadName);
                System.out.println(roadName);
            }
        }
        return invalidNameList;
    }
    public static boolean isValidOSMRoadName(String roadName, String continueName) throws InterruptedException {
        final String HIGHWAY_CONGESTION_LOCATION_LEFT = "https://jiaotong.baidu.com/trafficindex/city/roadcurve?cityCode=131&id=";
        for (int j = 0; j <= 10; j++) {
                System.out.println("roadName = " + roadName + ", seg_id = " + j);
                Thread.sleep(120);
                String roadSegID = "";
                roadSegID = roadSegID + "-" + String.valueOf(j);
                //long startTime = System.currentTimeMillis();
                String url = HIGHWAY_CONGESTION_LOCATION_LEFT + "&id=" + roadName + roadSegID;
                JSONObject jo = new JSONObject();
                try {
                    jo = JSON.parseObject(WebSpiderUtil.getJsonFromURL(url));
                    jo.getJSONObject("data");
                } catch (Exception e) {
                    continue;
                }
                String linkString = jo.getJSONObject("data").getString("links");
                String[] highwaySegmentArray = linkString.split("\\|");
                JSONArray ja = jo.getJSONObject("data").getJSONArray("location");
                try {
                    if(ja.size() == 0){
                        continue;
                    }
                } catch (NullPointerException e) {
                    continue;
                }
                return true;
            }
        return false;
    }
    public static void main(String args[]) throws SQLException, InterruptedException {
        JDBCUtil.startConnection();
        getInvalidRoadNameListFromOSM("马家堡中路");
//        for(String name: getInvalidRoadNameListFromOSM())
//        {
//            System.out.println(name);//getBeijingRoadNameFromAndSaveToDatabase(10, 1, 5, 375);
//        }
    }
}
